package com.hujing;

/**
 * 线程死锁例子测试
 */
public class ThreadDeadDemo {
    // 创建2个锁对象
    private static final Object lock1 = new Object();
    private static final Object lock2 = new Object();

    public static void main(String[] args) {
        // 线程1：先获取lock1，再尝试获取lock2
        Thread thread1 = new Thread(() -> {
            synchronized (lock1) {
                System.out.println("线程1已获取lock1，尝试获取lock2");
                try {
                    // 休眠段时间，让线程2获取到lock2
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lock2) {
                    System.out.println("线程1已获取lock2");
                }
            }
        });
        
        // 线程2：先获取lock2，再尝试获取lock1
        Thread thread2 = new Thread(() -> {
            synchronized (lock2) {
                System.out.println("线程2已获取lock2，尝试获取lock1");
                try {
                    // 休眠段时间，让线程1获取到lock1
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (lock1) {
                    System.out.println("线程2已获取lock1");
                }
            }
        });
        
        // 设置线程名
        thread1.setName("线程1");
        thread2.setName("线程2");
        
        // 启动线程
        thread1.start();
        thread2.start();
    }
}
